package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.mapper.PermissionMapper;
import org.javaweb.cms_web.model.ArticleDTO;
import org.javaweb.cms_web.model.Enum.PermissionTypes;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.model.UserPermission;
import org.javaweb.cms_web.service.ArticleManagementService;
import org.javaweb.cms_web.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class ArticleManagementController {

    @Autowired
    private ArticleManagementService articleManagementService;
    @Autowired
    private HostHolder hostHolder;
    @Resource
    private PermissionMapper permissionMapper;

    // 显示文章管理页面，展示所有文章
    @GetMapping("/admin/articlesManagement")
    public String showArticleManagementPage(@RequestParam(value = "searchKeyword", required = false) String searchKeyword,
                                            @RequestParam(value = "startDate", required = false) String startDate,
                                            @RequestParam(value = "endDate", required = false) String endDate,
                                            Model model) {
        User user = hostHolder.getUser();
        List<UserPermission> list=permissionMapper.getPermissionsByUserId(user.getUserId());
        if (list.stream().map(UserPermission::getPermissionType).
                noneMatch(type -> type == PermissionTypes.ARTICLE_MANAGE.value)) {
            return "nopermission";
        }
        // 获取筛选后的文章列表
        List<ArticleDTO> articles = articleManagementService.getFilteredArticles(searchKeyword, startDate, endDate);

        // 将筛选条件返回到页面
        model.addAttribute("articles", articles);
        model.addAttribute("searchKeyword", searchKeyword);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);

        return "article-management";  // 返回到文章管理页面
    }

    // 显示新文章发布页面
    @GetMapping("/admin/articles/new")
    public String showNewArticlePage(Model model) {
        model.addAttribute("article", new ArticleDTO());
        return "article-create";  // 返回到新文章发布页面
    }

    @PostMapping("/admin/articles")
    public String saveArticle(
            @ModelAttribute("article") ArticleDTO article,
            @RequestParam("attachmentFile") MultipartFile attachmentFile,
            Model model) {

        try {
            // 保存附件文件
            if (!attachmentFile.isEmpty()) {
                String attachmentPath = saveFile(attachmentFile, "D:\\keshedata\\ArticlesPicture\\");
                article.setAttachmentLink(attachmentPath); // 设置附件路径
            }


            Integer userid=hostHolder.getUser().getUserId();
            article.setUserId(userid);
            article.setTeamId(1);
            boolean success = articleManagementService.saveArticle(article);
            model.addAttribute("message", success ? "文章发布成功" : "文章发布失败");
        } catch (IOException e) {
            model.addAttribute("message", "文件上传失败：" + e.getMessage());
        }

        return "redirect:/admin/articlesManagement";
    }

    // 显示编辑页面
    @GetMapping("/admin/articles/edit/{articleId}")
    public String showEditPage(@PathVariable("articleId") Integer articleId, Model model) {
        ArticleDTO article = articleManagementService.getArticleById(articleId);
        model.addAttribute("article", article);
        return "article-edit";  // 显示编辑文章页面
    }

    @PostMapping("/admin/articles/edit")
    public String saveUpdatedArticle(
            @ModelAttribute("article") ArticleDTO article,
            @RequestParam(value = "attachmentFile", required = false) MultipartFile attachmentFile,
            Model model) {

        try {
            // 如果用户上传了新的附件文件
            if (attachmentFile != null && !attachmentFile.isEmpty()) {
                String attachmentPath = saveFile(attachmentFile, "D:\\keshedata\\ArticlesPicture\\");
                article.setAttachmentLink(attachmentPath); // 更新附件路径
            }

            Integer userid=hostHolder.getUser().getUserId();
            article.setUserId(userid);
            article.setTeamId(1);
            boolean success = articleManagementService.updateArticle(article);
            model.addAttribute("message", success ? "文章更新成功" : "文章更新失败");
        } catch (IOException e) {
            model.addAttribute("message", "文件上传失败：" + e.getMessage());
        }

        return "redirect:/admin/articlesManagement";
    }

    private String saveFile(MultipartFile file, String directory) throws IOException {
        File dir = new File(directory);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                throw new IOException("无法创建目录: " + directory);
            }
        }

        String fileName =  file.getOriginalFilename();
        File destination = new File(dir, fileName);
        file.transferTo(destination);

        return destination.getAbsolutePath();
    }

    // 删除文章
    @GetMapping("/admin/articles/delete/{articleId}")
    public String deleteArticle(@PathVariable("articleId") Integer articleId, Model model) {
        boolean success = articleManagementService.deleteArticle(articleId);
        if (success) {
            model.addAttribute("message", "文章删除成功");
        } else {
            model.addAttribute("message", "文章删除失败");
        }
        return "redirect:/admin/articlesManagement";  // 删除后重定向到文章管理页面
    }
}
